<!-- Layout.vue - 从后端数据库获取用户信息 -->
<template>
  <div class="container">
    <div class="sidebar">
      <!-- 侧边栏内容 -->
      <div class="sidebar-header">
        <h3>智慧农场</h3>
        <p>管理系统</p>
      </div>

      <!-- 删除农场概览菜单项 -->
      <div class="menu-item" :class="{ active: activeMenu === 'smart-home' }" @click="switchMenu('smart-home')">
        智慧家居
      </div>
      <div class="menu-item" :class="{ active: activeMenu === 'smart-planting' }" @click="switchMenu('smart-planting')">
        智慧种植
      </div>
      <div class="menu-item" :class="{ active: activeMenu === 'smart-pigsty' }" @click="switchMenu('smart-pigsty')">
        智慧猪舍
      </div>
      <div class="menu-item" :class="{ active: activeMenu === 'smart-pond' }" @click="switchMenu('smart-pond')">
        智慧鱼塘
      </div>
    </div>

    <div class="main-content">
      <div class="header">
        <div>
          <h3>{{ pageTitle }}</h3>
        </div>

        <div class="user-info" v-if="authStore.user">
          <!-- 修复：安全地访问用户信息 -->
          <div class="user-avatar" @click="goToUserProfile" style="cursor: pointer;">
            {{ getUserInitial(authStore.user) }}
          </div>
          <div @click="goToUserProfile" style="cursor: pointer;">
            <div>{{ getUserDisplayName(authStore.user) }}</div>
            <div style="font-size: 12px; color: #777;">{{ getDisplayRole(authStore.user.role) }}</div>
          </div>

          <!-- 关键修改：使用从后端获取的数据进行管理员角色判断 -->
          <button
              v-if="isUserAdmin"
              @click="goToAdmin"
              class="admin-btn"
              :disabled="loadingUserInfo"
          >
            {{ loadingUserInfo ? '加载中...' : '后台管理' }}
          </button>

          <button @click="handleLogout" class="logout-btn">
            退出
          </button>
        </div>

        <div class="user-info" v-else>
          <button @click="$router.push('/login')" style="margin-left: 15px; background: #48bb78; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">
            登录
          </button>
        </div>
      </div>

      <div class="content">
        <router-view></router-view>
      </div>
    </div>
  </div>
</template>

<script>
import { useAuthStore } from '@/stores/auth'
import { useRouter, useRoute } from 'vue-router'
import { computed, ref, watch, onMounted } from 'vue'

export default {
  name: 'Layout',
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()
    const route = useRoute()

    // 默认激活智慧家居菜单
    const activeMenu = ref('smart-home')
    const loadingUserInfo = ref(false)

    // 从后端数据库加载用户信息
    const loadUserInfoFromBackend = async () => {
      if (!authStore.user) {
        console.log('ℹ️ 用户未登录，跳过后端数据加载');
        return;
      }

      loadingUserInfo.value = true;
      try {
        console.log('🔄 Layout: 从后端数据库加载用户信息');
        const result = await authStore.refreshUserFromBackend();

        if (result.success) {
          console.log('✅ Layout: 用户信息加载成功', authStore.user);
          console.log('🎯 用户角色:', authStore.user.role);
          console.log('🛡️ 是否为管理员:', authStore.user.role === 'ROLE_ADMIN');
        } else {
          console.log('❌ Layout: 用户信息加载失败', result.message);
        }
      } catch (error) {
        console.error('💥 Layout: 加载用户信息异常', error);
      } finally {
        loadingUserInfo.value = false;
      }
    }

    // 安全获取用户首字母
    const getUserInitial = (user) => {
      if (!user) return 'U'
      const name = user.phone || user.username || '用户'
      return name.charAt(0).toUpperCase()
    }

    // 安全获取用户显示名称
    const getUserDisplayName = (user) => {
      if (!user) return '未知用户'
      return user.phone || user.username || '未知用户'
    }

    // 角色显示映射
    const getDisplayRole = (role) => {
      const roleDisplayMap = {
        'ROLE_ADMIN': '管理员',
        'ADMIN': '管理员',
        'USER': '用户',
        '用户': '用户'
      }
      return roleDisplayMap[role] || '用户'
    }

    // 基于后端数据的角色判断
    const isUserAdmin = computed(() => {
      return authStore.user?.role === 'ROLE_ADMIN';
    })

    const pageTitle = computed(() => {
      const titles = {
        'smart-home': '智慧家居',
        'smart-planting': '智慧种植',
        'smart-pigsty': '智慧猪舍',
        'smart-pond': '智慧鱼塘',
        'user-profile': '个人中心'
      }
      return titles[activeMenu.value] || '智慧农场管理系统'
    })

    const switchMenu = (menu) => {
      activeMenu.value = menu
      router.push(`/dashboard/${menu}`)
    }

    // 修复：跳转路径加上 /dashboard 父路由前缀
    const goToUserProfile = () => {
      activeMenu.value = 'user-profile'
      router.push('/dashboard/user-profile') // 正确路径：父路由+子路由
    }

    const goToAdmin = () => {
      router.push('/admin')
    }

    const handleLogout = () => {
      authStore.logout()
      router.push('/login')
    }

    // 组件挂载时从后端加载用户信息
    onMounted(() => {
      console.log('🚀 Layout 组件挂载，开始从后端数据库加载用户信息');
      loadUserInfoFromBackend();
    })

    // 监听路由变化
    watch(() => route.path, (newPath) => {
      const segments = newPath.split('/').filter(segment => segment)
      // 处理 user-profile 路由（ segments 结构：['dashboard', 'user-profile'] ）
      const menu = segments[1] || segments[0] || 'smart-home'

      if (menu === 'user-profile') {
        activeMenu.value = 'user-profile'
      } else if (menu) {
        activeMenu.value = menu
      }
    }, { immediate: true })

    // 监听用户信息变化
    watch(() => authStore.user, (newUser) => {
      if (newUser) {
        console.log('🔍 Layout用户信息更新:', {
          phone: newUser.phone,
          role: newUser.role,
          isAdmin: newUser.role === 'ROLE_ADMIN'
        })
      }
    }, { immediate: true })

    return {
      authStore,
      activeMenu,
      pageTitle,
      loadingUserInfo,
      isUserAdmin,
      switchMenu,
      handleLogout,
      goToUserProfile,
      goToAdmin,
      getDisplayRole,
      getUserInitial,
      getUserDisplayName,
      loadUserInfoFromBackend
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.container {
  display: flex;
  min-height: 100vh;
}

.sidebar {
  width: 220px;
  background: linear-gradient(180deg, #2d5a27, #1e3c1e);
  color: white;
  padding: 20px 0;
}

.sidebar-header {
  padding: 0 20px 20px;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 15px;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s;
  border-left: 4px solid transparent;
}

.menu-item:hover, .menu-item.active {
  background-color: rgba(255, 255, 255, 0.1);
  border-left-color: #48bb78;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: white;
  padding: 15px 25px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e2e8f0;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-weight: bold;
  transition: all 0.3s;
}

.user-avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
}

/* 新增：后台管理按钮样式 */
.admin-btn {
  background: #ed8936;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 15px;
  font-size: 0.9rem;
  transition: all 0.3s;
}

.admin-btn:hover:not(:disabled) {
  background: #dd7711;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(237, 137, 54, 0.3);
}

.admin-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 修改退出按钮样式，使其与后台管理按钮协调 */
.logout-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: #777;
  margin-left: 15px;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.logout-btn:hover {
  color: #e53e3e;
  background: rgba(229, 62, 62, 0.1);
}

.content {
  padding: 25px;
  flex: 1;
  overflow-y: auto;
}
</style>